import { Injectable, NotFoundException } from '@nestjs/common';
import { ProductService } from '../../product/service/product.service';
import { ProductDto } from '../../product/dto/product.dto';

export interface CartItem {
  product: ProductDto;
  quantity: number;
}

@Injectable()
export class CartService {
  private cartItems: CartItem[] = [];

  constructor(private readonly productService: ProductService) {}

  addItem(productId: string, quantity: number): string {
    const product = this.productService.findOne(productId);
    
    if (!product) {
      throw new NotFoundException(`商品 ID ${productId} 不存在`);
    }

    const existingItem = this.cartItems.find(item => item.product.id === productId);
    
    if (existingItem) {
      existingItem.quantity += quantity;
    } else {
      this.cartItems.push({ product, quantity });
    }

    return `商品《${product.name}》已添加到购物车`;
  }

  getItems(): CartItem[] {
    return this.cartItems;
  }
}